#include "./image2d.hpp"

#include "../input/input.hpp"

#include "../ui_message/message.h"

namespace qbe::image2d {

void init(ecs::Commands commands, ecs::Query query) {
  auto instance = Models::Instance();

  ecs::Query* static_query = query.get_resource<ecs::Query*>();

  if (instance == nullptr) {
    static Models models = Models(static_query);

    commands.insert_resource<Models*>(&models);
  } else {
    instance->setQuery(static_query);
    commands.insert_resource<Models*>(instance);
  }

  // auto& models_t = query.get_resource<Models>();
  // models_t.setInstance(&models_t);
}

void test(ecs::Query query, ecs::Bus& bus) {
  ecs::Query* static_query = query.get_resource<ecs::Query*>();

  auto instance = Models::Instance();
  instance->setQuery(static_query);

  bool value = getKeyPressed("view", "Zoom in on the area", bus);

  if (value) {
    value = false;
  }

  // auto& models = query.get_resource<Models>();

  // auto receive = bus.receive<qbe::UiMessage::GetImage2D>();
  // if (!receive.empty()) {
  //   qlib::Reference::s_ptr refer = receive.back().refer;
  //   int width = receive.back().width;
  //   int height = receive.back().height;

  //   QImage image = models.saveImage2d(refer, width, height);

  //   qbe::UiMessage::Image2D send_event;
  //   send_event.image = image;

  //   bus.send(send_event);
  // }

  // auto& handModule = query.get_resource<vsg::ref_ptr<input::HandleBundle>>();

  // if (handModule->mousePressed(vsg::ButtonMask::BUTTON_MASK_1)) {
  //   // models.saveImage2d(0, 255, 255);
  // }
}

void Plugin::build(ecs::App& app) {
  app.add_stage<InitStage>();
  app.add_systems<InitStage>(init);

  app.add_stage<UpdateStage>();
  app.add_systems<ecs::stage::Update>(test);
}
}  // namespace qbe::image2d